﻿using System.Collections.Generic;
using Yoozoo.Framework.Core;

namespace WorldMapBase.Display
{
    public class DisplayManager: Singleton<DisplayManager>
    {
        /// <summary>
        /// 展示元素链表
        /// </summary>
        private LinkedList<ILegacyDisplayElement> m_DisplayElements = new LinkedList<ILegacyDisplayElement>();

        /// <summary>
        /// 单次处理计时
        /// </summary>
        private readonly System.Diagnostics.Stopwatch m_Stopwatch = new System.Diagnostics.Stopwatch();

        /// <summary>
        /// 单次处理最大耗时
        /// </summary>
        private const int MAX_PER_FRAME_CONSUME_TIME = 10;

        /// <summary>
        /// 添加展示元素
        /// </summary>
        public static void AddDisplayElement(ILegacyDisplayElement element)
        {
            p_instance.m_DisplayElements.AddLast(element);
        }

        /// <summary>
        /// 移除展示元素
        /// </summary>
        /// <param name="element"></param>
        public static void RemoveDisplayElement(ILegacyDisplayElement element)
        {
            p_instance.m_DisplayElements.Remove(element);
        }

        public override void Update()
        {
            base.Update();
            Refresh();
        }

        /// <summary>
        /// 刷新
        /// </summary>
        public void Refresh()
        {
            if (p_instance.m_DisplayElements == null)
            {
                return;
            }

            p_instance.m_Stopwatch.Stop();
            p_instance.m_Stopwatch.Reset();
            p_instance.m_Stopwatch.Start();
            while (p_instance.m_DisplayElements.Count > 0 && p_instance.m_Stopwatch.ElapsedMilliseconds < MAX_PER_FRAME_CONSUME_TIME)
            {
                ILegacyDisplayElement displayElement = p_instance.m_DisplayElements.First.Value;
                displayElement.Refresh();
                p_instance.m_DisplayElements.RemoveFirst();                
            }
            p_instance.m_Stopwatch.Stop();
        }
    }
}